package com.sevattal.service.leaves.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sevattal.common.base.result.ResultCodeEnum;
import com.sevattal.service.base.exception.SevattalException;
import com.sevattal.service.leaves.entity.Prov;
import com.sevattal.service.leaves.mapper.ProvMapper;
import com.sevattal.service.leaves.service.ProvService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 供应商表 服务实现类
 * </p>
 *
 * @author Sevattal
 * @since 2021-08-28
 */
@Service
public class ProvServiceImpl extends ServiceImpl<ProvMapper, Prov> implements ProvService {

    @Override
    public boolean createProv(Prov prov) {
        if (prov.getFPid() == null || StringUtils.isEmpty(prov.getFPid()) ||
                prov.getFPname() == null || StringUtils.isEmpty(prov.getFPname())){
            throw new SevattalException(ResultCodeEnum.PARAM_ERROR);
        }
        QueryWrapper<Prov> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("f_pId",prov.getFPid());
        int count = baseMapper.selectCount(queryWrapper);
        if (count != 0){
            throw new SevattalException(ResultCodeEnum.PARAM_ERROR);
        }
        int result = baseMapper.insert(prov);
        return result == 1;
    }

    @Override
    public boolean updateProv(Prov prov) {
        if (prov.getFPid() == null || StringUtils.isEmpty(prov.getFPid()) ||
                prov.getFPname() == null || StringUtils.isEmpty(prov.getFPname())){
            throw new SevattalException(ResultCodeEnum.PARAM_ERROR);
        }
        QueryWrapper<Prov> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("f_pId",prov.getFPid());
        int count = baseMapper.selectCount(queryWrapper);
        if (count == 0){
            throw new SevattalException(ResultCodeEnum.PARAM_ERROR);
        }
        int result = baseMapper.update(prov,queryWrapper);
        return result == 1;
    }

    @Override
    public boolean deleteProv(String id) {
        QueryWrapper<Prov> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("f_pId",id);
        int result = baseMapper.delete(queryWrapper);
        return result == 1;
    }

    @Override
    public List<Prov> getProvList(Prov prov) {
        QueryWrapper<Prov> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("f_pId");
        if (prov.getFPid() != null && !StringUtils.isEmpty(prov.getFPid())){
            queryWrapper.like("f_pId",prov.getFPid());
        }
        if (prov.getFPname() != null && !StringUtils.isEmpty(prov.getFPname())) {
            queryWrapper.like("f_pName", prov.getFPname());
        }
        List<Prov> provList = baseMapper.selectList(queryWrapper);
        return provList;
    }
}
